import * as cheerio from "cheerio";
import { loadEnvContent } from "./../scripts/load_env.js";
export default function (module = "developement") {

    return {
        name: "vite-plugin-html-injecet",
        transformIndexHtml(html, ctx) {
            let envContent = loadEnvContent();
            const $ = cheerio.load(html);
            let insertStr = "";
            let styleList = [];
            let scriptList = [];
            if (envContent.HEAD_STYLE && envContent.HEAD_STYLE.length > 0) {
                styleList = [...styleList, ...envContent.HEAD_STYLE];
            };
            if (envContent.HEAD_SCRIPT && envContent.HEAD_SCRIPT.length > 0) {
                scriptList = [...scriptList, ...envContent.HEAD_SCRIPT];

            }

            if (module == "developement") {
                if(envContent.DEVELOPOMENT_HEAD_STYLE && envContent.DEVELOPOMENT_HEAD_STYLE.length > 0){
                    styleList = [...styleList, ...envContent.DEVELOPOMENT_HEAD_STYLE];
                };
                if(envContent.DEVELOPOMENT_HEAD_SCRIPT && envContent.DEVELOPOMENT_HEAD_SCRIPT.length > 0){
                    scriptList = [...scriptList, ...envContent.DEVELOPOMENT_HEAD_SCRIPT];
                };
            } else if (module == "publish") {
                if(envContent.PUBLISH_HEAD_STYLE && envContent.PUBLISH_HEAD_STYLE.length > 0){
                    styleList = [...styleList, ...envContent.PUBLISH_HEAD_STYLE];
                };
                if(envContent.PUBLISH_HEAD_SCRIPT && envContent.PUBLISH_HEAD_SCRIPT.length > 0){
                    scriptList = [...scriptList, ...envContent.PUBLISH_HEAD_SCRIPT];
                };
            };


            if (styleList.length > 0) {
                styleList.forEach((styleItem) => {
                    insertStr += `<link rel="stylesheet" href="${styleItem}">`
                });
            };
            if (scriptList.length > 0) {
                scriptList.forEach((scriptItem) => {
                    insertStr += `\n<script type="text/javascript" src="${scriptItem}"></script>`;
                });
            }


            (insertStr.length > 0) && $(insertStr).insertAfter("title");
            return $.html();

        },

    }
};